package com.ruyuan.gateway.server.filter;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 继承默认的filter，复用它的大部分能力，只对拦截后的行为做个修改，并不是完全替代它
 * @author xx
 */
@Component("authc")
public class RuyuanGatewayAuthenticationFilter extends FormAuthenticationFilter {

    @Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        // 只对异步请求的接口进行改造
        if (StringUtils.isNotBlank(((HttpServletRequest)request).getHeader("Referer"))) {
            ((HttpServletResponse) response).setHeader("session-expired", "true");
            ((HttpServletResponse) response).setStatus(403);
        } else {
            super.redirectToLogin(request, response);
        }
    }
}
